<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateParkChannelsAPIRequest;
use App\Http\Requests\API\UpdateParkChannelsAPIRequest;
use App\Models\ParkChannels;
use App\Repositories\ParkChannelsRepository;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use DB;
use Overtrue\Http\Client;

/**
 * Class ParkChannelsController
 * @package App\Http\Controllers\API
 */

class ParkChannelsAPIController extends AppBaseController
{
    /** @var  ParkChannelsRepository */
    private $parkChannelsRepository;

    public function __construct(ParkChannelsRepository $parkChannelsRepo)
    {
        $this->parkChannelsRepository = $parkChannelsRepo;
    }

    /**
     * Display a listing of the ParkChannels.
     * GET|HEAD /parkChannels
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $this->parkChannelsRepository->pushCriteria(new RequestCriteria($request));
        $this->parkChannelsRepository->pushCriteria(new LimitOffsetCriteria($request));
        $parkChannels = $this->parkChannelsRepository->all();

        return $this->sendResponse($parkChannels->toArray(), '查询成功');
    }

    /**
     * Store a newly created ParkChannels in storage.
     * POST /parkChannels
     *
     * @param CreateParkChannelsAPIRequest $request
     *
     * @return Response
     */
    public function store(CreateParkChannelsAPIRequest $request)
    {
        $input = $request->all();

        $parkChannels = $this->parkChannelsRepository->create($input);

        return $this->sendResponse($parkChannels->toArray(), '请求成功');
    }

    /**
     * Display the specified ParkChannels.
     * GET|HEAD /parkChannels/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        /** @var ParkChannels $parkChannels */
        $parkChannels = $this->parkChannelsRepository->findWithoutFail($id);

        if (empty($parkChannels)) {
            return $this->sendError('车道未找到');
        }

        return $this->sendResponse($parkChannels->toArray(), '查询成功');
    }

    /**
     * Update the specified ParkChannels in storage.
     * PUT/PATCH /parkChannels/{id}
     *
     * @param  int $id
     * @param UpdateParkChannelsAPIRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateParkChannelsAPIRequest $request)
    {
        $input = $request->all();

        /** @var ParkChannels $parkChannels */
        $parkChannels = $this->parkChannelsRepository->findWithoutFail($id);

        if (empty($parkChannels)) {
            return $this->sendError('车道未找到');
        }

        $parkChannels = $this->parkChannelsRepository->update($input, $id);

        return $this->sendResponse($parkChannels->toArray(), '请求成功');
    }

    /**
     * Remove the specified ParkChannels from storage.
     * DELETE /parkChannels/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        /** @var ParkChannels $parkChannels */
        $parkChannels = $this->parkChannelsRepository->findWithoutFail($id);

        if (empty($parkChannels)) {
            return $this->sendError('车道未找到');
        }

        $parkChannels->delete();

        return $this->sendResponse($id, '删除成功');
    }

    public function liftingLever(Request $request)
    {
        $url = config('remoteControl.park_channel_lift');
        $client = Client::create();

        $armCode = $request->get('arm_code');
        $parkCode = $request->get('park_code');
        // 出入口
        $gateWay  = $request->get('gateway');
        if($gateWay == 1) {    //  1:出口
            $gateWay=2;
        } else if($gateWay == 2) {    //  2:入口
            $gateWay=1;
        }

        // gateway 出入口 1:出口 2:入口
        if (empty($armCode) || empty($parkCode) || empty($gateWay)) {
            return $this->sendApiError('参数异常');
        }

        $requestData = [
            'arm_code' => $armCode,
            'park_code' => $parkCode,
            // 出入口
            'gatway' => $gateWay,
            'type' => 1,

        ];
        try {
            $response = $client->post($url, $requestData);
        } catch (ClientException $e) {
            throw $e;
        }
        return $this->sendResponse($response, '请求成功');
    }

    /*
     *  即时模式
     */
    public function sendLiftCode(Request $request){
        $this->validate($request, [
            'park_code' => 'required',
            'arm_code' => 'required',
            'gatway' => 'required',
            'flag'=>'required'    //   1 抬 0 不抬
        ]);
        $url = config('remoteControl.park_order_lift');
        $client = Client::create();

        $armCode = $request->get('arm_code');
        $parkCode = $request->get('park_code');
        $flag = $request->get('flag');
        $order_statu = $request->get('order_statu',0);
        // 出入口
        $gateWay  = $request->get('gatway');
        if($gateWay == 1) {    //  1:出口
            $out_site_type = 2;
            $gateWay=140;
        } else if($gateWay == 2) {    //  2:入口
            $out_site_type = 1;
            $gateWay=139;
        }
        $requestData = [
            'group_name' => "one",
            'arm_code' => $armCode,
            'park_code' => $parkCode,
            'protocol' => '{"ocflag":'.$flag.',"channel":'.$out_site_type.'}'
        ];
        $response = [];
        try {
            $this->log("Liftpole send a message：".json_encode($requestData));
            $response = $client->post($url, $requestData);
            $this->log("Liftpole received a message：".json_encode($response));
            if($order_statu == 0 && $response['code']==0) {
                $r = DB::table('park_channels')
                    ->where('park_code', $parkCode)
                    ->where('arm_code', $armCode)
                    ->where('type', $gateWay)
                    ->update([
                        'nflag' => $flag,
                    ]);
                return $this->sendResponse($response, '操作成功');
            } else if($response['code']==0 && $order_statu == 1) {
                $r = DB::update("update park_channels set flag=0,order_start=NULL,order_end=NULL where park_code='$parkCode' and arm_code='$armCode' and type='$gateWay'");
                return $this->sendResponse([], '操作成功');
            } else {
                return $this->sendError( '开启失败');
            }
        } catch (ClientException $e) {
            return $this->sendError([], '开启失败');
        }
        return $this->sendResponse($response, '操作成功');
    }

    /*
     *  添加预约车队时间
     */
    public function addOrderCar(Request $request){
        $this->validate($request, [
            'park_code' => 'required',
            'arm_code' => 'required',
            'gatway'=>'required',    //   出入口 1:出口 2:入口
        ]);
        $armCode = $request->get('arm_code');
        $parkCode = $request->get('park_code');
        $rtime = $request->get('rtime');
        $gatway = $request->get('gatway');
        $order_statu = $request->get('order_statu',0);

        //139 入口  140 出口
        if($gatway == 2) {
            $gatway = 139;
        } else if($gatway == 1) {
            $gatway=140;
        }
        if($order_statu == 0) {
            $r = DB::table('park_channels')
                ->where('park_code', $parkCode)
                ->where('arm_code', $armCode)
                ->where('type', $gatway)
                ->update([
                    'flag' => 0,
                    'order_start' => date('Y-m-d H:i:s', $rtime[0]),
                    'order_end' => date('Y-m-d H:i:s', $rtime[1])
                ]);
        } else if($order_statu == 1) {
            $r = DB::update("update park_channels set flag=0,order_start=NULL,order_end=NULL where park_code='$parkCode' and arm_code='$armCode' and type='$gatway'");
        }

        return $this->sendResponse([], '操作成功');

    }
}
